package com.sparrow.common.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.function.Consumer;

public class FileUtil {

    /**
     * 根据路径获取文件
     * @param path 文件路径
     * @return 文件对象
     */
    public static File getFile(String path) {
        URL url = FileUtil.class.getClassLoader().getResource(path);
        if (url == null) {
            throw new IllegalArgumentException("文件路径 " + path + " 对应的资源未找到");
        }
        File file = new File(url.getFile());
        if (!file.exists()) {
            throw new IllegalArgumentException("文件路径 " + path + " 不存在");
        }
        return file;
    }

    /**
     * 读取文本文件内容到字符串
     * @param absPath 文件的绝对路径
     * @return 文件内容的字符串表示
     * @throws IOException 读取文件时发生 I/O 错误
     */
    public static String readFileContent(String absPath) throws IOException {
        try (BufferedReader reader = new BufferedReader(new FileReader(absPath))) {
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line).append("\n");
            }
            return result.toString();
        }
    }

    /**
     * 写入字符串到文件，此操作是覆盖型操作
     * @param absPath 文件的绝对路径
     * @param content 要写入的内容
     * @throws IOException 写入文件时发生 I/O 错误
     */
    public static void writeFile(String absPath, String content) throws IOException {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(absPath))) {
            writer.write(content);
        }
    }

    /**
     * 判断文件或文件夹是否存在
     * @param path 文件或文件夹的路径
     * @return 如果存在返回 true，否则返回 false
     */
    public static boolean exist(String path) {
        return new File(path).exists();
    }

    /**
     * 复制文件夹
     * @param oldAbsFileName 源文件夹的绝对路径
     * @param newAbsFileName 目标文件夹的绝对路径
     * @throws IOException 复制过程中发生 I/O 错误
     */
    public static void copyFolder(String oldAbsFileName, String newAbsFileName) throws IOException {
        Path source = Paths.get(oldAbsFileName);
        Path target = Paths.get(newAbsFileName);

        if (!Files.exists(source)) {
            throw new IOException("源文件夹不存在: " + oldAbsFileName);
        }

        if (!Files.exists(target)) {
            Files.createDirectories(target);
        }

        Files.walk(source)
                .forEach(sourcePath -> {
                    try {
                        Path targetPath = target.resolve(source.relativize(sourcePath));
                        if (Files.isDirectory(sourcePath)) {
                            Files.createDirectories(targetPath);
                        } else {
                            Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
                        }
                    } catch (IOException e) {
                        throw new RuntimeException("复制文件时发生错误", e);
                    }
                });
    }

    public static void delete(File f) {
        if (f == null || !f.exists()) {
            return;
        }
        if (f.isDirectory()) {
            File[] files = f.listFiles();
            if (files != null) {
                for (File file : files) {
                    delete(file); // 递归删除
                }
            }
        } else {
            f.delete();
        }
    }


    public static void walk(Path path, Consumer<Path> consumer) {
        try {
            Files.walk(path).forEach(consumer);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        Path dir = Paths.get("D:\\Users\\Desktop\\temp");
        walk(dir, e -> {
            System.out.println(e.toString());
        });
    }
}